<template>
  <el-amap
    ref="map"
    map-style="amap://styles/62009be025f187dd3eafe327d2e55b8e"
    :center="center"
    :zoom="zoom"
    view-mode="2D"
    class="amap-demo"
    @init="initMap"
    @click="clickMap"
  >
    <el-amap-search-box placeholder="请输入关键字" @select="selectPoi" :visible="true"/>
    <el-amap-control-scale />
    <el-amap-control-tool-bar />
    <el-amap-marker
      v-for="(marker, index) in markers"
      :key="index"
      :position="marker.position"
    />
  </el-amap>
</template>

<script>
export default {
  name: "MapPicker",
  model: {
    prop: "value",
    event: "update",
  },
  props: {
    value: Array,
  },
  data() {
    return {
      mapObj: null,
      zoom: 12,
      center: [112.551315, 37.864679],
      markers: [],
      loading: true,
    };
  },
  mounted() {
    if (this.value && this.value.length === 2) {
      const [lng, lat] = this.value;
      if (lng && lat) {
        this.markers = [
          {
            position: this.value,
            id: 1,
          },
        ];
      }
    }
  },
  methods: {
    selectPoi(e) {
      const {poi: {location: {lng, lat}, name}} = e
      this.$emit("update", [lng, lat]);
      this.mapObj.setZoomAndCenter(12,[lng, lat])
      this.markers = [
        {
          position: [lng, lat],
          id: 1,
        },
      ];
      this.$emit("detail-address", name);
    },
    clickMap(e) {
      const {
        lnglat: { lat, lng },
      } = e;
      this.$emit("update", [lng, lat]);
      this.markers = [
        {
          position: [lng, lat],
          id: 1,
        },
      ];
      window.AMap.plugin("AMap.Geocoder", () => {
        const geocoder = new AMap.Geocoder({});
        geocoder.getAddress([lng, lat], (status, result) => {
          if (status === "complete" && result.info === "OK") {
            const {
              regeocode: { formattedAddress },
            } = result;
            if (formattedAddress) {
              this.$emit("detail-address", formattedAddress);
            }
          }
        });
      });
    },
    initMap(e) {
      this.mapObj = e;
      this.loading = false;
      if (this.value && this.value.length === 2) {
        const [lng, lat] = this.value;
        if (lng && lat) {
          this.mapObj.setZoomAndCenter(12,[lng, lat])
        }
      }

    },
  },
};
</script>

<style scoped>
.amap-demo {
  height: 300px;
}
</style>
<style>
.amap-sug-result {
  z-index: 1000000 !important;
}
</style>
